package com.youlai.boot.factory.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.youlai.boot.factory.mapper.ProcessTemplateDetailMapper;
import com.youlai.boot.factory.mapper.ProcessTemplateMapper;
import com.youlai.boot.factory.model.entity.ProcessTemplateDetail;
import com.youlai.boot.factory.model.vo.ImportStyleProcessVo;
import com.youlai.boot.factory.service.ProcessTemplateService;
import lombok.RequiredArgsConstructor;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.boot.factory.mapper.StyleProcessMapper;
import com.youlai.boot.factory.service.StyleProcessService;
import com.youlai.boot.factory.model.entity.StyleProcess;
import com.youlai.boot.factory.model.form.StyleProcessForm;
import com.youlai.boot.factory.model.query.StyleProcessQuery;
import com.youlai.boot.factory.model.vo.StyleProcessVO;
import com.youlai.boot.factory.converter.StyleProcessConverter;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import org.springframework.transaction.annotation.Transactional;

/**
 * 款号工序关联服务实现类
 *
 * @author youlaitech
 * @since 2025-10-06 11:07
 */
@Service
@RequiredArgsConstructor
public class StyleProcessServiceImpl extends ServiceImpl<StyleProcessMapper, StyleProcess> implements StyleProcessService {

    private final StyleProcessConverter styleProcessConverter;

    /**
     * 获取款号工序关联分页列表
     *
     * @param queryParams 查询参数
     * @return {@link IPage<StyleProcessVO>} 款号工序关联分页列表
     */
    @Override
    public IPage<StyleProcessVO> getStyleProcessPage(StyleProcessQuery queryParams) {
        Page<StyleProcessVO> pageVO = this.baseMapper.getStyleProcessPage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
        return pageVO;
    }


    /**
     * 获取款号工序关联分页列表-关联工序列表
     *
     * @param queryParams 查询参数
     * @return {@link IPage<StyleProcessVO>} 款号工序关联分页列表-关联工序列表
     */
    @Override
    public IPage<StyleProcessVO> getStyleProcessJoinPage(StyleProcessQuery queryParams) {
        Page<StyleProcessVO> pageVO = this.baseMapper.getStyleProcessJoinPage(
                new Page<>(queryParams.getPageNum(), queryParams.getPageSize()),
                queryParams
        );
        return pageVO;
    }


    /**
     * 获取款号工序关联表单数据
     *
     * @param id 款号工序关联ID
     * @return 款号工序关联表单数据
     */
    @Override
    public StyleProcessForm getStyleProcessFormData(Long id) {
        StyleProcess entity = this.getById(id);
        return styleProcessConverter.toForm(entity);
    }

    @Autowired
    private StyleProcessMapper styleProcessMapper;

    /**
     * 新增款号工序关联
     *
     * @param formData 款号工序关联表单对象
     * @return 是否新增成功
     */
    @Override
    public boolean saveStyleProcess(StyleProcessForm formData) {
        //查询款的工序列表 如果process_id 和 即将新增的process_id 相同，则不允许新增
        List<StyleProcess> styleProcessList = styleProcessMapper.selectList(
                new LambdaQueryWrapper<StyleProcess>()
                        .eq(StyleProcess::getStyleId, formData.getStyleId())
                        .eq(StyleProcess::getProcessId, formData.getProcessId())
        );
        Assert.isTrue(styleProcessList.isEmpty(), "该款中已存在该工序");
        StyleProcess entity = styleProcessConverter.toEntity(formData);
        return this.save(entity);
    }

    /**
     * 更新款号工序关联
     *
     * @param id       款号工序关联ID
     * @param formData 款号工序关联表单对象
     * @return 是否修改成功
     */
    @Override
    public boolean updateStyleProcess(Long id, StyleProcessForm formData) {
        //查询款的工序列表 如果process_id 和 即将新增的process_id 相同，则不允许新增
        List<StyleProcess> styleProcessList = styleProcessMapper.selectList(
                new LambdaQueryWrapper<StyleProcess>()
                        .eq(StyleProcess::getStyleId, formData.getStyleId())
                        .eq(StyleProcess::getProcessId, formData.getProcessId())
                        .ne(StyleProcess::getId, id) // 排除当前正在更新的记录
        );

        Assert.isTrue(styleProcessList.isEmpty(), "该款中已存在该工序");
        StyleProcess entity = styleProcessConverter.toEntity(formData);
        return this.updateById(entity);
    }

    /**
     * 删除款号工序关联
     *
     * @param ids 款号工序关联ID，多个以英文逗号(,)分割
     * @return 是否删除成功
     */
    @Override
    public boolean deleteStyleProcesss(String ids) {
        Assert.isTrue(StrUtil.isNotBlank(ids), "删除的款号工序关联数据为空");
        // 逻辑删除
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(Long::parseLong)
                .toList();
        return this.removeByIds(idList);
    }

    @Autowired
    private ProcessTemplateDetailMapper processTemplateDetailMapper;


    /**
     * 根据工序模板id批量导入工序
     *
     * @param id 工序模板id
     * @return 是否导入成功
     */
    @Override
    @Transactional
    public int importStyleProcess(ImportStyleProcessVo importStyleProcessVo) {
        //先根据模板id查询出工序列表
        processTemplateDetailMapper.selectList(new QueryWrapper<ProcessTemplateDetail>().eq("template_id", importStyleProcessVo.getProcessTemplateId()));

        List<ProcessTemplateDetail> processTemplateDetails = processTemplateDetailMapper.selectList(new QueryWrapper<ProcessTemplateDetail>().eq("template_id", importStyleProcessVo.getProcessTemplateId()));

        //组装好styleProcessList
        List<StyleProcess> styleProcessList = processTemplateDetails.stream().map(processTemplateDetail -> {
            StyleProcess styleProcess = new StyleProcess();
            styleProcess.setProcessId(processTemplateDetail.getProcessId());
            styleProcess.setCustomPrice(processTemplateDetail.getUnitPrice());
            styleProcess.setCreateTime(LocalDateTime.now());
            styleProcess.setStyleId(importStyleProcessVo.getStyleId());
            return styleProcess;
        }).collect(Collectors.toList());

        // 查询出来款原本的工序列表 如果有和即将导入的工序列表相同的 删除掉
        List<StyleProcess> existingStyleProcesses = styleProcessMapper.selectList(new QueryWrapper<StyleProcess>().eq("style_id", importStyleProcessVo.getStyleId()));

        // 找出需要删除的记录ID（与即将导入的工序ID相同的记录）
        List<Long> idsToDelete = existingStyleProcesses.stream()
                .filter(existingProcess -> styleProcessList.stream()
                        .anyMatch(newProcess -> newProcess.getProcessId().equals(existingProcess.getProcessId())))
                .map(StyleProcess::getId)
                .collect(Collectors.toList());

        // 批量删除重复的记录
        if (!idsToDelete.isEmpty()) {
            styleProcessMapper.deleteBatchIds(idsToDelete);
        }

        return styleProcessMapper.insertBatch(styleProcessList);
    }


}
